// DOM 加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    initializeAdmin();
});

// 初始化管理员页面
function initializeAdmin() {
    checkAdminPermission();
    setupEventListeners();
    loadAllFunctions();
    loadAllCarModelsForCreate();
    loadUserList();
}

// 检查管理员权限
function checkAdminPermission() {
    const isAdmin = localStorage.getItem('is_admin') === 'true';
    if (!isAdmin) {
        showNotification('您没有管理员权限', 'error');
        setTimeout(() => {
            window.location.href = '/dashboard';
        }, 2000);
    }
}

// 设置事件监听器
function setupEventListeners() {
    // 创建用户表单
    const createUserForm = document.getElementById('createUserForm');
    createUserForm.addEventListener('submit', handleCreateUser);
    
    // 登出按钮
    const logoutBtn = document.getElementById('logoutBtn');
    logoutBtn.addEventListener('click', handleLogout);
}

// 加载所有功能列表
async function loadAllFunctions() {
    try {
        const response = await fetch('/api/all-functions', {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            }
        });
        
        const data = await response.json();
        
        if (data.functions) {
            renderFunctionPermissions(data.functions);
        }
    } catch (error) {
        console.error('加载功能列表失败:', error);
        showNotification('加载功能列表失败', 'error');
    }
}

// 渲染功能权限选项
function renderFunctionPermissions(functions) {
    const container = document.getElementById('functionPermissions');
    container.innerHTML = '';
    
    functions.forEach(function(func) {
        const option = document.createElement('div');
        option.className = 'function-option flex items-center p-3 border border-gray-200 rounded-lg cursor-pointer hover:bg-gray-50';
        option.innerHTML = `
            <input type="checkbox" class="custom-checkbox mr-3" id="admin_func_${func}" value="${func}">
            <label for="admin_func_${func}" class="text-sm text-gray-700 cursor-pointer">${func}</label>
        `;
        
        // 添加点击事件
        option.addEventListener('click', function(e) {
            if (e.target.type !== 'checkbox') {
                const checkbox = this.querySelector('input[type="checkbox"]');
                checkbox.checked = !checkbox.checked;
            }
        });
        
        container.appendChild(option);
    });
}

// 加载所有车型列表（用于创建用户）
async function loadAllCarModelsForCreate() {
    try {
        const response = await fetch('/api/all-car-models', {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            }
        });
        const data = await response.json();
        const container = document.getElementById('carModelPermissions');
        container.innerHTML = '';
        (data.car_models || []).forEach(model => {
            const option = document.createElement('div');
            option.className = 'function-option flex items-center p-3 border border-gray-200 rounded-lg cursor-pointer hover:bg-gray-50';
            option.innerHTML = `
                <input type="checkbox" class="custom-checkbox mr-3" id="create_car_${model}" value="${model}">
                <label for="create_car_${model}" class="text-sm text-gray-700 cursor-pointer">${model}</label>
            `;
            option.addEventListener('click', function(e) {
                if (e.target.type !== 'checkbox') {
                    const checkbox = this.querySelector('input[type="checkbox"]');
                    checkbox.checked = !checkbox.checked;
                }
            });
            container.appendChild(option);
        });
    } catch (error) {
        console.error('加载车型列表失败:', error);
        showNotification('加载车型列表失败', 'error');
    }
}

// 处理创建用户
async function handleCreateUser(e) {
    e.preventDefault();
    const username = document.getElementById('newUsername').value.trim();
    const email = document.getElementById('newEmail').value.trim();
    const password = document.getElementById('newPassword').value;
    const generateLimit = document.getElementById('newGenerateLimit').value;
    // 获取选中的功能
    const selectedFunctions = [];
    document.querySelectorAll('#functionPermissions input[type="checkbox"]:checked').forEach(checkbox => {
        selectedFunctions.push(checkbox.value);
    });
    // 获取选中的车型
    const selectedCarModels = [];
    document.querySelectorAll('#carModelPermissions input[type="checkbox"]:checked').forEach(checkbox => {
        selectedCarModels.push(checkbox.value);
    });
    // 验证输入
    if (!username || !email || !password) {
        showNotification('请填写所有必填字段', 'error');
        return;
    }
    if (password.length < 6) {
        showNotification('密码长度至少6位', 'error');
        return;
    }
    // 显示加载状态
    showLoading(true);
    try {
        const formData = new FormData();
        formData.append('username', username);
        formData.append('email', email);
        formData.append('password', password);
        formData.append('generate_limit', generateLimit);
        selectedFunctions.forEach(func => {
            formData.append('functions', func);
        });
        selectedCarModels.forEach(car => {
            formData.append('car_models', car);
        });
        const response = await fetch('/api/create-user', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            },
            body: formData
        });
        const result = await response.json();
        if (result.success) {
            showNotification('用户创建成功！', 'success');
            document.getElementById('createUserForm').reset();
            loadUserList();
        } else {
            showNotification(result.detail || '创建用户失败', 'error');
        }
    } catch (error) {
        console.error('创建用户失败:', error);
        showNotification('创建用户失败，请重试', 'error');
    } finally {
        showLoading(false);
    }
}

// 加载用户列表
async function loadUserList() {
    try {
        const response = await fetch('/api/users', {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            }
        });
        
        const data = await response.json();
        
        if (data.users) {
            renderUserList(data.users);
        }
    } catch (error) {
        console.error('加载用户列表失败:', error);
        showNotification('加载用户列表失败', 'error');
    }
}

// 渲染用户列表时缓存数据
function renderUserList(users) {
    window._userListCache = users;
    const container = document.getElementById('userList');
    if (users.length === 0) {
        container.innerHTML = `
            <div class="text-center text-gray-500 py-8">
                <i class="fas fa-users text-4xl mb-2"></i>
                <p>暂无用户</p>
            </div>
        `;
        return;
    }
    container.innerHTML = users.map(user => `
        <div class="border border-gray-200 rounded-lg p-4 hover:bg-gray-50 transition-colors">
            <div class="flex justify-between items-start">
                <div class="flex-1">
                    <div class="flex items-center space-x-3 mb-2">
                        <h3 class="font-medium text-gray-800">${user.username}</h3>
                        ${user.is_admin ? '<span class="bg-blue-100 text-blue-800 text-xs px-2 py-1 rounded">管理员</span>' : ''}
                        ${user.is_active ? '<span class="bg-green-100 text-green-800 text-xs px-2 py-1 rounded">活跃</span>' : '<span class="bg-red-100 text-red-800 text-xs px-2 py-1 rounded">禁用</span>'}
                    </div>
                    <p class="text-sm text-gray-600 mb-2">${user.email}</p>
                    <p class="text-xs text-gray-500">创建时间: ${new Date(user.created_at).toLocaleString()}</p>
                    <p class="text-xs text-gray-500">剩余生成次数: <span class="font-mono">${user.generate_limit}</span></p>
                    ${user.functions && user.functions.length > 0 ? `
                        <div class="mt-2">
                            <p class="text-xs text-gray-500 mb-1">功能权限:</p>
                            <div class="flex flex-wrap gap-1">
                                ${user.functions.map(func => `<span class="bg-gray-100 text-gray-700 text-xs px-2 py-1 rounded">${func}</span>`).join('')}
                            </div>
                        </div>
                    ` : ''}
                    ${user.car_models && user.car_models.length > 0 ? `
                        <div class="mt-2">
                            <p class="text-xs text-gray-500 mb-1">车型权限:</p>
                            <div class="flex flex-wrap gap-1">
                                ${user.car_models.map(car => `<span class="bg-gray-100 text-gray-700 text-xs px-2 py-1 rounded">${car}</span>`).join('')}
                            </div>
                        </div>
                    ` : ''}
                </div>
                <div class="flex space-x-2">
                    <button 
                        onclick="editUser('${user.id}')"
                        class="text-blue-600 hover:text-blue-800 text-sm"
                        title="编辑用户"
                    >
                        <i class="fas fa-edit"></i>
                    </button>
                    <button 
                        onclick="toggleUserStatus('${user.id}', ${user.is_active})"
                        class="${user.is_active ? 'text-red-600 hover:text-red-800' : 'text-green-600 hover:text-green-800'} text-sm"
                        title="${user.is_active ? '禁用用户' : '启用用户'}"
                    >
                        <i class="fas fa-${user.is_active ? 'ban' : 'check'}"></i>
                    </button>
                </div>
            </div>
        </div>
    `).join('');
}

// 编辑用户弹窗
let editingUserId = null;
function editUser(userId) {
    const user = window._userListCache.find(u => u.id == userId);
    if (!user) return;
    editingUserId = userId;
    let html = `<div id="editUserModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-40">
        <div class="bg-white rounded-xl shadow-xl p-8 w-full max-w-lg relative">
            <button id="closeEditModal" class="absolute top-3 right-3 text-gray-400 hover:text-gray-700 text-xl">&times;</button>
            <h3 class="text-xl font-bold mb-4">编辑用户权限 - ${user.username}</h3>
            <form id="editUserForm" class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">功能权限</label>
                    <div id="editFunctionPermissions" class="grid grid-cols-2 md:grid-cols-3 gap-2"></div>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">车型权限</label>
                    <div id="editCarModelPermissions" class="grid grid-cols-2 md:grid-cols-3 gap-2"></div>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">生成次数</label>
                    <input type="number" id="editGenerateLimit" name="generate_limit" class="w-full px-4 py-2 border border-gray-300 rounded" min="1" value="${user.generate_limit || 100}">
                </div>
                <div class="flex justify-end">
                    <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-lg">保存</button>
                </div>
            </form>
        </div>
    </div>`;
    document.body.insertAdjacentHTML('beforeend', html);
    loadAllFunctionsForEdit(user.functions);
    loadAllCarModelsForEdit(user.car_models || user.carModels || []);
    document.getElementById('closeEditModal').onclick = closeEditUserModal;
    document.getElementById('editUserForm').onsubmit = submitEditUserForm;
}
function closeEditUserModal() {
    const modal = document.getElementById('editUserModal');
    if (modal) modal.remove();
    editingUserId = null;
}
async function loadAllFunctionsForEdit(selected) {
    const resp = await fetch('/api/all-functions', {headers: {'Authorization': `Bearer ${localStorage.getItem('access_token')}`}});
    const data = await resp.json();
    const container = document.getElementById('editFunctionPermissions');
    container.innerHTML = '';
    (data.functions || []).forEach(func => {
        const checked = selected.includes(func) ? 'checked' : '';
        container.innerHTML += `<label class="flex items-center"><input type="checkbox" value="${func}" class="mr-2" ${checked}>${func}</label>`;
    });
}
async function loadAllCarModelsForEdit(selected) {
    const resp = await fetch('/api/all-car-models', {headers: {'Authorization': `Bearer ${localStorage.getItem('access_token')}`}});
    const data = await resp.json();
    const container = document.getElementById('editCarModelPermissions');
    container.innerHTML = '';
    (data.car_models || []).forEach(model => {
        const checked = selected.includes(model) ? 'checked' : '';
        container.innerHTML += `<label class="flex items-center"><input type="checkbox" value="${model}" class="mr-2" ${checked}>${model}</label>`;
    });
}
async function submitEditUserForm(e) {
    e.preventDefault();
    const functions = Array.from(document.querySelectorAll('#editFunctionPermissions input[type=checkbox]:checked')).map(i=>i.value);
    const car_models = Array.from(document.querySelectorAll('#editCarModelPermissions input[type=checkbox]:checked')).map(i=>i.value);
    const generate_limit = document.getElementById('editGenerateLimit').value;
    const formData = new FormData();
    formData.append('user_id', editingUserId);
    functions.forEach(f=>formData.append('functions', f));
    car_models.forEach(c=>formData.append('car_models', c));
    formData.append('generate_limit', generate_limit);
    showLoading(true);
    try {
        const resp = await fetch('/api/update-user', {
            method: 'POST',
            headers: {'Authorization': `Bearer ${localStorage.getItem('access_token')}`},
            body: formData
        });
        const data = await resp.json();
        if (data.success) {
            showNotification('用户权限已更新', 'success');
            closeEditUserModal();
            loadUserList();
        } else {
            showNotification(data.detail || '更新失败', 'error');
        }
    } catch (e) {
        showNotification('更新失败', 'error');
    } finally {
        showLoading(false);
    }
}
// 禁用/启用用户
async function toggleUserStatus(userId, currentStatus) {
    if (!confirm(`确定要${currentStatus ? '禁用' : '启用'}这个用户吗？`)) return;
    const formData = new FormData();
    formData.append('user_id', userId);
    showLoading(true);
    try {
        const resp = await fetch('/api/toggle-user-status', {
            method: 'POST',
            headers: {'Authorization': `Bearer ${localStorage.getItem('access_token')}`},
            body: formData
        });
        const data = await resp.json();
        if (data.success) {
            showNotification(`${data.is_active ? '启用' : '禁用'}成功`, 'success');
            loadUserList();
        } else {
            showNotification(data.detail || '操作失败', 'error');
        }
    } catch (e) {
        showNotification('操作失败', 'error');
    } finally {
        showLoading(false);
    }
}

// 处理登出
function handleLogout() {
    if (confirm('确定要退出登录吗？')) {
        // 清除本地存储
        localStorage.removeItem('access_token');
        localStorage.removeItem('username');
        localStorage.removeItem('is_admin');
        localStorage.removeItem('remember_me');
        
        // 跳转到登录页
        window.location.href = '/login';
    }
}

// 显示/隐藏加载状态
function showLoading(show) {
    const loadingOverlay = document.getElementById('loadingOverlay');
    if (show) {
        loadingOverlay.classList.remove('hidden');
    } else {
        loadingOverlay.classList.add('hidden');
    }
}

// 显示通知
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `fixed top-4 right-4 z-50 p-4 rounded-lg shadow-lg transform transition-all duration-300 translate-x-full`;
    
    // 根据类型设置样式
    switch (type) {
        case 'success':
            notification.className += ' bg-green-500 text-white';
            break;
        case 'error':
            notification.className += ' bg-red-500 text-white';
            break;
        case 'warning':
            notification.className += ' bg-yellow-500 text-white';
            break;
        default:
            notification.className += ' bg-blue-500 text-white';
    }
    
    notification.innerHTML = `
        <div class="flex items-center">
            <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'} mr-2"></i>
            <span>${message}</span>
        </div>
    `;
    
    document.body.appendChild(notification);
    
    // 显示动画
    setTimeout(() => {
        notification.classList.remove('translate-x-full');
    }, 100);
    
    // 自动隐藏
    setTimeout(() => {
        notification.classList.add('translate-x-full');
        setTimeout(() => {
            if (document.body.contains(notification)) {
                document.body.removeChild(notification);
            }
        }, 300);
    }, 3000);
}
